package traditionalthread;

public class ThreadSafeModel {

	private String accountNo;
	
	//private double balance;
	
	private ThreadLocal<Double> balance1 = new ThreadLocal<Double>();
	public ThreadSafeModel(){}

	public ThreadSafeModel(String accountNo, double balance) {
		this.accountNo = accountNo;
		this.balance1.set(balance);
	}
	
    public double getBalance(){
    	return this.balance1.get();
    }
    
    public synchronized void draw(double drawAmount){
    	double balance =getBalance();
    	if(balance>=drawAmount){
    		System.out.println(Thread.currentThread().getName()+" 取钱成功，取出金额为 "+drawAmount);
    		balance-=drawAmount;
    		balance1.set(balance);
    		System.out.println(Thread.currentThread().getName()+" 余额为 "+balance);
    	}else{
    		System.out.println(Thread.currentThread().getName()+" 余额不足，取钱失败！");
    	}
    }

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((accountNo == null) ? 0 : accountNo.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ThreadSafeModel other = (ThreadSafeModel) obj;
		if (accountNo == null) {
			if (other.accountNo != null)
				return false;
		} else if (!accountNo.equals(other.accountNo))
			return false;
		return true;
	}
	
}
